# coding=utf-8
# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import functools
from sqlalchemy import create_engine, Column, String, Integer, Index
from sqlalchemy.schema import ForeignKeyConstraint, ForeignKey
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declarative_base, declared_attr, as_declarative, DeclarativeMeta
from sqlalchemy.orm import sessionmaker, relationship, scoped_session
from core.db.base import BaseModel


class User(BaseModel):
    id = Column(Integer(), primary_key=True, autoincrement=True)
    name = Column(String(20), unique=True, nullable=False, index=True)
    first_name = Column(String(30), nullable=True, default='Nothing')
    last_name = Column(String(30), nullable=True, default='null')

    __table_args__ = (Index('user_index', 'first_name', "last_name"),)

    # order_by 即返回时的排序规则
    @declared_attr
    def address(cls):
        return relationship("Address", back_populates='user', order_by='Address.id')

    def __repr__(self):
        return "<" + self.name + " object>"


class Address(BaseModel):
    __tablename__ = "tb_address"
    id = Column(Integer(), primary_key=True, autoincrement=True)
    address = Column(String(30), nullable=False)

    # 关联的外键ID, 需要存储的
    user_id = Column(Integer, ForeignKey(User.__tablename__ + ".id"))

    # 外键的关联关系
    @declared_attr
    def user(cls):
        return relationship("User", back_populates='address')

    def __repr__(self):
        return "<" + self.address + " object>"
